{% extends 'base_pages/base.html' %}

{% block title %}
{{_("Dev Containers Management")}}
{% endblock %}

{% block header %}
<h1>{{_("Dev Containers Management")}}</h1>
{% endblock %}

{% block content %}
<button onclick="openModal()">{{_("Create New...")}}</button>

<table id="container-list">
    <thead>
        <tr>
            <th>{{_("Container Name")}}</th>
            <th>{{_("User")}}</th>
            <th>{{_("Host")}}</th>
            <th>{{_("Dev Env Name")}}</th>
            <th>{{_("Status")}}</th>
            <th>{{_("Image")}}</th>
            <th>{{_("Ports")}}</th>
            <th>{{_("Actions")}}</th>
        </tr>
    </thead>
    <tbody>
        {% for container, user, host_machine, dev_env_info in containers|zip4(users, host_machines, dev_env_info_list)
        %}
        <tr>
            <td>{{ container['name'] }}</td>
            <td>{{ user }}</td>
            <td>{{ host_machine['name'] }}</td>
            <td>{{ dev_env_info.name }}</td>
            <td>{{ container['status'] }}</td>
            <td>
                {% if container['image'] | split(',') | length > 1 %}
                <div class="image-container">
                    <p style="margin-block-start: 0.3em; margin-block-end: 0.3em">{{ container['image'] | split(',') |
                        first | stripSpaces() | strip("'\"") }}</p>
                    <div class="image-dropdown" style="display: none;">
                        {% for containerImage in container['image'] | split(',') %}
                        <p class="copyable-image" style="margin-block-start: 0.3em; margin-block-end: 0.3em">{{
                            containerImage | stripSpaces() | strip("'\"") }}</p>
                        {% endfor %}
                    </div>
                    <button class="show-more-images">{{ _("More") }}</button>
                </div>
                {% else %}
                <p style="margin-block-start: 0.3em; margin-block-end: 0.3em">{{ container['image'] | split(',') | first
                    | stripSpaces() | strip("'\"") }}</p>
                {% endif %}
            </td>
            <td>
                <p style="margin-block-start: 0.3em; margin-block-end: 0.3em">{{dev_env_info.ide}}</p>
                {% for containerPort, hostPort in dev_env_info.ports.items() %}
                <p style="margin-block-start: 0.3em; margin-block-end: 0.3em">{{ hostPort }} -> {{ containerPort }}</p>
                {% endfor %}
            </td>
            <td>
                {% if dev_env_info.url!="" %}
                <button {% if container.status=='exited' %} disabled {% endif %}
                    onclick="openEditor(`{{ dev_env_info.url }}`)">{{ _("Open Editor") }}</button>
                {% endif %}
                <div class="action-menu">
                    <button class="menu-toggle">{{ _("Actions") }}</button>
                    <div class="menu-content">
                        <button onclick="renameContainer('{{ container.name }}', '{{ host_machine.id }}')">{{
                            _("Rename") }}</button>
                        <button {% if container.status=='running' %} disabled {% endif %}
                            onclick="startContainer('{{ container.name }}','{{ host_machine.id }}')">{{ _("Start")
                            }}</button>
                        <button {% if container.status=='exited' %} disabled {% endif %}
                            onclick="stopContainer('{{ container.name }}', '{{ host_machine.id }}')">{{ _("Stop")
                            }}</button>

                        <!-- <button onclick="createSnapshot('{{ container.name }}', '{{ host_machine.id }}')">{{ _("Create
                            Snapshot") }}</button> -->
                    </div>
                </div>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
<!-- task_logs.html -->
{% include 'components/task_logs.html' %}
<!-- The Modal -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal()">&times;</span>
        <h2>{{ _("Create New Dev Env") }}</h2>
        <form id="createContainerForm">
            <!-- New input for container name -->
            <label for="devEnvName">{{ _("Dev Env Name:") }}</label><br>
            <input type="text" id="devEnvName" name="devEnvName" required 
            placeholder="{{_('A name with a-z, 0-9 and some symbols(_-.). Note that double minus (&quot;--&quot;) is not allowed.')}}"><br><br>

            <label for="portMapping">{{ _("Port Mapping:") }}</label><br>
            <input type="text" id="portMapping" name="portMapping"
                placeholder="{{_('like &quot;8080:80&quot; (not including the quotes), use &quot;,&quot; to separate multiple mappings')}}"><br><br>

            <!-- New checkbox for allowing container Docker operations -->
            <!-- <label for="allowDockerOps">{{ _("Allow container to operate Docker:") }}</label>
            <input type="checkbox" id="allowDockerOps" name="allowDockerOps"><br><br> -->


            <!-- New dropdown for selecting the container image -->
            <label for="developmentEnvImg">{{ _("Development Environment:") }}</label>
            <select id="developmentEnvImg" name="developmentEnvImg">
                <!-- Options will be populated dynamically -->
            </select><br><br>

            <!-- New dropdown for selecting the host machine -->
            <label for="hostMachine">{{ _("Host Machine:") }}</label>
            <select id="hostMachine" name="hostMachine">
                <option value="">{{ _("None") }}</option>
                <!-- Options will be populated dynamically -->
            </select><br><br>

            <!-- New dropdown for selecting the virtual network -->
            <label for="network">{{ _("Network:") }}</label>
            <select id="network" name="network">
                <option value="">{{ _("None") }}</option>
                <!-- Add more network options as needed -->
            </select><br><br>

            <!-- New dropdown for setting the ip -->
            <label for="containerIP">{{ _("Container IP:") }}</label>
            <input type="text" id="containerIP" name="containerIP"
                placeholder="{{_('Must be a legal IP under the selected network (or the default network if &quot;network&quot; is None). If unset, the IP will be assigned randomly.')}}"><br><br>

            <!-- New dropdown for selecting the proxy type -->
            <label for="proxyType">{{ _("Proxy Type:") }}</label>
            <select id="proxyType" name="proxyType">
                <option value="http-dedicated-port">{{_("Dedicated Port")}}</option>
                <option value="http-subroute">{{_("Subroute")}}</option>
            </select><br><br>

            <input type="button" value="{{ _('Confirm') }}" onclick="createContainer()">
        </form>
    </div>
</div>

<script>
    function imgNamesFormatter(imgNames) {
        console.log(imgNames)
        return imgNames
    }

    function openEditor(newURL) {
        console.log(newURL)
        window.open(newURL, '_blank')
    }
    function startContainer(containerName, hostMachineID) {
        apiFetch('/container_mgr/start', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                containerName,
                hostMachineID
            })
        }).then(() => location.reload());
    }

    function stopContainer(containerName, hostMachineID) {
        apiFetch('/container_mgr/stop', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                containerName,
                hostMachineID // Assuming a function to get host_machine_id
            })
        }).then(() => location.reload());
    }

    // Function to fetch development environments and populate the dropdown
    function fetchDevelopmentEnvironments() {
        apiFetch('/dev_env_imgs/dev_env_imgs')
            .then(response => response.json())
            .then(data => {
                const developmentEnvDropdown = document.getElementById('developmentEnvImg');
                developmentEnvDropdown.replaceChildren([])
                data.forEach((env, index) => {
                    const option = document.createElement('option');
                    option.value = env.id; // Assuming 'id' is the unique identifier for each environment
                    option.textContent = `${index + 1}. ${env.name}`; // Display as "序号+名称"
                    developmentEnvDropdown.appendChild(option);
                });
            })
            .catch(error => console.error('Error fetching development environments:', error));
    }

    // Function to fetch host machines and populate the dropdown
    function fetchHostMachines() {
        return new Promise((resolve, reject) => apiFetch('/host-machine-info')
            .then(response => response.json())
            .then(data => {

                hostMachineDropdown.replaceChildren([]);
                data.forEach((host, index) => {
                    const option = document.createElement('option');
                    option.value = host.id; // Assuming 'id' is the unique identifier for each host
                    option.textContent = `${index + 1}. ${host.name}`; // Display as "序号+名称"
                    hostMachineDropdown.appendChild(option);
                });

                // 当主机选择变化时，动态更新虚拟网络下拉菜单
                hostMachineDropdown.addEventListener('change', () => {
                    const selectedHost = hostMachineDropdown.options[hostMachineDropdown.selectedIndex].textContent.split('. ')[1];
                    updateVirtualNetworkDropdown(selectedHost);
                });
                resolve();
            })
            .catch(error => { console.error('Error fetching host machines:', error); reject(); }));
    }
    const hostMachineDropdown = document.getElementById('hostMachine');
    hostMachineDropdown.addEventListener('change', () => {
        const selectedHost = hostMachineDropdown.options[hostMachineDropdown.selectedIndex].textContent.split('. ')[1];
        updateVirtualNetworkDropdown(selectedHost);
    });

    // 全局变量，用于存储所有主机的网络信息
    let networksData = {};

    // Function to fetch available networks of all host machines
    function fetchNetworks() {
        return new Promise((resolve, reject) => apiFetch('/host-machine-info/get_all_networks')
            .then(response => response.json())
            .then(data => {
                networksData = data.data; // 存储所有主机的网络信息
                // Now dispatch a change event to initialize the dropdown
                resolve();
            })
            .catch(error => {
                console.error('Error fetching networks:', error);
                reject();
            }));
    }

    // Function to update the virtual network dropdown based on the selected host
    function updateVirtualNetworkDropdown(selectedHost) {
        const virtualNetworkDropdown = document.getElementById('network');
        virtualNetworkDropdown.replaceChildren([]);
        const hostNetworks = networksData[selectedHost] || [];

        // 添加默认选项 "None"
        const noneOption = document.createElement('option');
        noneOption.value = '';
        noneOption.textContent = '{{ _("None") }}';
        virtualNetworkDropdown.appendChild(noneOption);

        // 动态添加主机对应的网络选项
        hostNetworks.forEach(network => {
            const option = document.createElement('option');
            option.value = network.name;
            // console.log(JSON.stringify(network));
            // console.log(JSON.stringify(network.ipam.Config), (network.ipam.Config != null && network.ipam.Config.length > 0 && network.ipam.Config[0] != null));
            option.textContent = `Name: ${network.name}, Driver: ${network.driver}, `
            if (network.ipam.Config != null && network.ipam.Config.length > 0 && network.ipam.Config[0] != null) {
                option.textContent += `Subnet: ${network.ipam.Config[0].Subnet}, Gateway: ${network.ipam.Config[0].Gateway}`;
            }
            virtualNetworkDropdown.appendChild(option);
        });
    }

    // Call the function to populate the dropdown when the modal is opened
    function openModal() {
        document.getElementById("myModal").style.display = "block";
        fetchDevelopmentEnvironments(); // Fetch and populate the dropdown
        Promise.all([fetchHostMachines(), // Fetch and populate the host machine dropdown
        fetchNetworks() // Fetch and store network data
        ]).then(() => {
            hostMachineDropdown.dispatchEvent(new Event('change'));
        })
    }

    function closeModal() {
        document.getElementById("myModal").style.display = "none";
    }
    // Function to create a new development environment
    function createContainer() {
        const devEnvName = document.getElementById("devEnvName").value; // Get container name
        const portMapping = document.getElementById("portMapping").value;
        // <!-- const allowDockerOps = document.getElementById("allowDockerOps").checked; -->
        const network = document.getElementById("network").value;
        const developmentEnvImgID = document.getElementById("developmentEnvImg").value.split(".")[0].trim(); // Change parameter name to developmentEnvID
        const proxyType = document.getElementById("proxyType").value;
        const hostId = document.getElementById("hostMachine").value; // Get host ID
        const containerIP = document.getElementById("containerIP").value;

        apiFetch('/container_mgr/start_create_dev_env', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                devEnvName: devEnvName, // Include container name in the request
                portMapping: portMapping,
                // allowDockerOps: allowDockerOps,
                network: network,
                developmentEnvImgID: developmentEnvImgID,
                proxyType: proxyType,
                containerIP: containerIP,
                hostId: hostId // Include host ID in the request
            })
        }).then(response => {
            if (response.ok) {
                response.json().then(data => {
                    console.log(data);
                    this.closeModal();
                    openTaskLogModal(data.task_id)
                })
                // <!-- message -->
                // <!-- alert('{{ _("Started the background task on the creation of your development environment.") }}'); -->

            } else {
                response.json().then(data => {
                    console.error(data);
                    alert('{{ _("Failed to create container") }}' + ": " + data.error);
                });

            }
        }).catch(error => {
            console.error('Error:', error);
            alert(`Failed to create container: ${error}`);
        });
    }

    function renameContainer(devEnvName, hostMachineID) {
        const newName = prompt("请输入新的容器名称:");
        if (newName) {
            apiFetch('/container_mgr/rename_container', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    devEnvName: devEnvName,
                    newName: newName,
                    hostMachineID: hostMachineID
                })
            }).then(response => {
                if (response.ok) {

                    location.reload();
                } else {
                    alert('{{ _("Failed to rename container") }}');
                }
            }).catch(error => {
                console.error('Error:', error);
                alert('{{ _("Failed to rename container") }}');
            });
        }
    }

    function createSnapshot(containerName, hostMachineID) {
        alert("Not implemented yet...")
        return
        const snapshotName = prompt("请输入快照名称:");
        if (snapshotName) {

            apiFetch('/container_mgr/create_snapshot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    snapshotName,
                    containerName,
                    hostMachineID: hostMachineID // 传递主机 ID
                })
            }).then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    response.json().then((data) => {
                        alert(data.error);
                    });
                }
            }).catch(error => {
                console.error('Error:', error);
                alert(error);
            });
        }
    }

    // Function to handle showing more images
    document.addEventListener('click', function (event) {
        if (event.target.classList.contains('show-more-images')) {
            const dropdown = event.target.previousElementSibling;
            dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
            event.target.innerText = event.target.innerText === "{{ _('More') }}" ? "{{ _('Less') }}" : "{{ _('More') }}";
        } else if (event.target.classList.contains('copyable-image')) {
            const text = event.target.textContent;
            navigator.clipboard.writeText(text).then(function () {
                alert('Copied to clipboard: ' + text);
            }, function (err) {
                console.error('Could not copy text: ', err);
            });
        }
    });

</script>
{% endblock %}